﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace WirelessAccessPoint.Interactivity
{
    /// <summary>
    /// 入力文字をトリムするモードです。
    /// </summary>
    public enum TrimMode
    {
        /// <summary>
        /// トリムしません。
        /// </summary>
        None,

        /// <summary>
        /// 先頭、末尾をトリムします。
        /// </summary>
        Both,

        /// <summary>
        /// 先頭をトリムします。
        /// </summary>
        Start,

        /// <summary>
        /// 末尾をトリムします。
        /// </summary>
        End
    }

    /// <summary>
    /// TextBoxがLostFocusする際に入力文字をトリムするビヘイビアです。
    /// 
    /// 【使用方法】
    /// <i:Interaction.Behaviors>
    ///     <behavior:TrimTextBoxBehavior TrimMode="Both" />
    /// </i:Interaction.Behaviors>
    /// </summary>
    public class TrimTextBoxBehavior : Behavior<TextBox>
    {
        public static readonly DependencyProperty TrimModeProperty = DependencyProperty.Register(
            "TrimMode",
            typeof(TrimMode),
            typeof(TrimTextBoxBehavior),
            new FrameworkPropertyMetadata(TrimMode.Both));

        public TrimMode TrimMode
        {
            get { return (TrimMode) this.GetValue(TrimModeProperty); }
            set { this.SetValue(TrimModeProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.LostKeyboardFocus += this.LostKeyboardFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.LostKeyboardFocus -= this.LostKeyboardFocus;
        }

        private void LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var associatedObject = sender as TextBox;

            if (associatedObject.Text != null)
            {
                switch (this.TrimMode)
                {
                    case TrimMode.Both:
                        associatedObject.Text = associatedObject.Text.Trim();
                        break;

                    case TrimMode.Start:
                        associatedObject.Text = associatedObject.Text.TrimStart();
                        break;

                    case TrimMode.End:
                        associatedObject.Text = associatedObject.Text.TrimEnd();
                        break;
                }
            }
        }
    }
}
